<template>
  <div class="header">Register</div>
  <div class="form-wrapper">
    <input type="text" name="username" placeholder="username" class="input-item" />
    <input type="password" name="password" placeholder="password" class="input-item" />
    <div class="btn" @click="subRegister">Register</div>
  </div>
  <div class="msg">
    Have account?
    <a href="#" @click="login">Login</a>
  </div>
</template>

<script setup>
import { register } from '@/api/userRegister'

import { userStatus } from '@/stores/userStatus'
import { ref, defineProps } from 'vue'
import { useRouter } from 'vue-router'

const userStore = ref(userStatus())
const router = useRouter()

const props = defineProps({
  func: {
    type: Function,
    default: () => {}
  }
})

const subRegister = () => {
  const username = document.querySelector('input[name="username"]').value
  const password = document.querySelector('input[name="password"]').value
  if (!validatePassword(password)) {
    alert('密码不符合要求。必须至少8个字符，包含至少一个数字和一个字母。')
    return
  }
  const form = {
    userName: username,
    userPassword: password
  }
  register(form)
    .then((res) => {
      const data = res.data.data
      userStore.value.hasLogin = true
      userStore.value.userName = username
      userStore.value.token = data.token
      // 登录成功跳转，返回上一层路由
      router.push('/')
    })
    .catch((err) => {
      console.log(err)
    })
}

const login = () => {
  props.func()
}

const validatePassword = (password) => {
  // 示例验证规则：至少8个字符，包含至少一个数字和一个字母
  const regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/

  return regex.test(password)
}
</script>

<style scoped lang="scss">
.header {
  font-size: 38px;
  font-weight: bold;
  text-align: center;
  line-height: 200px;
}
.input-item {
  display: block;
  width: 100%;
  margin-bottom: 20px;
  border: 0;
  padding: 10px;
  border-bottom: 1px solid rgb(128, 125, 125);
  font-size: 15px;
  outline: none;
}
.input-item:placeholder {
  text-transform: uppercase;
}
.btn {
  text-align: center;
  padding: 10px;
  width: 100%;
  margin-top: 40px;
  background-image: linear-gradient(to right, #a6c1ee, #fbc2eb);
  color: #fff;
}
.msg {
  text-align: center;
  line-height: 88px;
}
a {
  text-decoration-line: none;
  color: #abc1ee;
}
</style>
